package com.zxx.mvpPractice.model.net;

import com.zxx.mvpPractice.BuildConfig;
import com.zxx.mvpPractice.app.Constants;
import com.zxx.mvpPractice.utils.KL;
import com.zxx.mvpPractice.utils.SystemUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Description: RetrofitHelper
 * Creator: yxc
 * date: 2016/9/21 10:03
 */
public class RetrofitHelper {


    private static OkHttpClient OkHttpClient = null;

    private static BombApi bombApi;
    private static RongyunApi rongyunApi;

    private static Retrofit retrofit;
    private static final int DEFAULT_TIMEOUT = 5;

    public static BombApi getBombLoinApi() {
        initBmobOkHttp();
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttpClient)
                .baseUrl(BombApi.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //增加返回值为String的支持
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
        bombApi = retrofit.create(BombApi.class);
        return bombApi;
    }

    public static RongyunApi getRongyunApi() {
        initBmobOkHttp();
        Retrofit retrofit = new Retrofit.Builder()
                .client(OkHttpClient)
                .baseUrl(RongyunApi.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //增加返回值为String的支持
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
        rongyunApi = retrofit.create(RongyunApi.class);
        return rongyunApi;
    }


    private static void initBmobOkHttp() {
        if (OkHttpClient != null)
            return;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }
        File cacheFile = new File(Constants.PATH_CACHE);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        builder.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR);
        builder.addInterceptor(REWRITE_RESPONSE_INTERCEPTOR_OFFLINE);
        builder.addInterceptor(Third_RESPONSE_INTERCEPTOR);
        //设置缓存
        builder.cache(cache);
//            //设置超时
//            builder.connectTimeout(10, TimeUnit.SECONDS);
//            builder.readTimeout(20, TimeUnit.SECONDS);
//            builder.writeTimeout(20, TimeUnit.SECONDS);
//            //错误重连
//            builder.retryOnConnectionFailure(true);
        OkHttpClient = builder.build();
    }


    private static final Interceptor Third_RESPONSE_INTERCEPTOR = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {

            Request request = chain.request();
            request = request.newBuilder()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                    .addHeader("Content-Type", "application/json")
                    .addHeader("X-Bmob-Application-Id", BombApi.applicationId)
                    .addHeader("App-Key", RongyunApi.App_Key)
                    .addHeader("X-Bmob-REST-API-Key", BombApi.resetApiKey).build();
            return chain.proceed(request);
        }
    };

    private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            okhttp3.Response originalResponse = chain.proceed(chain.request());
            String cacheControl = originalResponse.header("Cache-Control");
            if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
                    cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, max-age=" + 5000)
                        .build();
            } else {
                return originalResponse;
            }
        }
    };

    private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR_OFFLINE = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!SystemUtils.isNetworkConnected()) {
                request = request.newBuilder()
                        .header("Cache-Control", "public, only-if-cached")
                        .build();
            }
            return chain.proceed(request);
        }
    };

}
